package liuds.music.view;

import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import liuds.music.R;
import liuds.music.utils.Utils;


public class LoadingDialog extends Dialog{
    //private TextView msgView;
    public int width= Utils.dip2px(100),height= Utils.dip2px(100);
    private static LoadingDialog currShow;
    private LoadingDialog(Context context) {
        //super(context,R.style.dialog);
        super(context, R.style.loading);
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); 充许点击其它地方
        initView();
    }
    public static boolean isLoading(){
        return currShow!=null;
    }
    public static void showLoading(Context context){
        LoadingDialog ld=new LoadingDialog(context);
        ld.show();
    }
    public static void showLoading(Context context,String message){
        LoadingDialog ld=new LoadingDialog(context);
        ld.setTitle(message);
        ld.show();
    }
    public static void showLoading(Context context,View inView){
        if(inView==null){
            showLoading(context);
        }else{
            LoadingDialog ld=new LoadingDialog(context);
            int[]position=new int[2];//相对于窗口x,y
            int width=inView.getWidth();
            int height=inView.getHeight();
            inView.getLocationOnScreen(position);

            int x=position[0]+(width-ld.width)/2;
            int y=position[1]+(height-ld.height)/2;
            ld.setLocation(x, y);
            ld.show();
        }

    }
    public void setLocation(int x,int y){
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        this.getWindow() .setGravity(Gravity.LEFT | Gravity.TOP);
        lp.x = x; // 新位置X坐标
        lp.y = y; // 新位置Y坐标
        this.getWindow().setAttributes(lp);
    }
    public static void hideAll(){
        if(currShow!=null){
            currShow.dismiss();
        }
    }
    @Override
    public void show() {
        if(currShow!=null){
            currShow.dismiss();
        }
        super.show();
        currShow=this;
    }
    @Override
    public void dismiss() {
        super.dismiss();
        currShow=null;
    }

    private void initView() {
        setCancelable(false);
        LinearLayout ll=new LinearLayout(getContext());
        ll.setBackgroundResource(R.drawable.loading);
        ll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        ll.setGravity(Gravity.CENTER);

        ProgressBar progressBar=new ProgressBar(getContext());
        ll.addView(progressBar);
        setContentView(ll);

        getWindow().setLayout(width, height);
    }

}
